package com.project.demo.controller;

import com.project.demo.entity.Feedback;
import com.project.demo.service.FeedbackService;
import com.project.demo.controller.base.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Map;

/**
 * 用户反馈：(Feedback)表控制层
 */
@Slf4j
@RestController
@RequestMapping("feedback")
public class FeedbackController extends BaseController<Feedback, FeedbackService> {
    
    @Autowired
    public FeedbackController(FeedbackService service) {
        setService(service);
    }

    /**
     * 添加反馈（重写add方法，自动设置创建时间）
     */
    @PostMapping("/add")
    @Transactional
    public Map<String, Object> add(HttpServletRequest request) throws IOException {
        Map<String, Object> body = service.readBody(request.getReader());
        
        // 设置创建时间
        if (body.get("create_time") == null) {
            body.put("create_time", new Timestamp(System.currentTimeMillis()));
        }
        
        // 设置处理状态为未处理
        if (body.get("is_processed") == null) {
            body.put("is_processed", 0);
        }
        
        // 验证码验证
        String captcha = (String) body.get("captcha");
        String captchaId = (String) body.get("captcha_id");
        
        if (captcha != null && !captcha.isEmpty() && captchaId != null) {
            // 从session获取验证码
            HttpSession session = request.getSession();
            String sessionKey = "captcha_" + captchaId;
            String sessionCode = (String) session.getAttribute(sessionKey);
            Long sessionTime = (Long) session.getAttribute(sessionKey + "_time");
            
            // 检查验证码是否存在或过期（5分钟）
            if (sessionCode == null || 
                (sessionTime != null && System.currentTimeMillis() - sessionTime > 5 * 60 * 1000)) {
                return error(30001, "验证码已过期，请刷新验证码");
            }
            
            // 验证码不区分大小写
            if (!sessionCode.equalsIgnoreCase(captcha)) {
                return error(30002, "验证码错误");
            }
            
            // 验证成功后删除验证码
            session.removeAttribute(sessionKey);
            session.removeAttribute(sessionKey + "_time");
        }
        
        // 移除验证码相关字段，这些字段不需要保存到数据库
        body.remove("captcha");
        body.remove("captcha_id");
        
        service.insert(body);
        log.info("收到新的用户反馈，邮箱：{}，标题：{}", body.get("email"), body.get("title"));
        
        return success(1);
    }
}

